﻿namespace WMS6.BLL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using WMS6.Common;
    using WMS6.DALFactory;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;
    using WMS6.DALFactory;

    public class AdjustmentBLL
    {
        private static readonly IAdjustmentDA adjustmentDA = DataAccess.CreateAdjustmentDA();
        private static readonly IAdjustmentDetailDA adjustmentdetailDA = DataAccess.CreateAdjustmentDetailDA();
        private static readonly ICommonMethodDA commonMethod = DataAccess.CreateCommonMethod();
        private List<string> dataBaseID;
        private static readonly IInvLotDA invLot = DataAccess.CreateInvLotDA();
        private static readonly IInvLotLocLpnDA invLotLocLpn = DataAccess.CreateInvLotLocLpnDA();
        private static readonly IInvSkuLocDA invskuloc = DataAccess.CreateInvSkuLocDA();
        private static readonly IInvTransDA invTranDA = DataAccess.CreateInvTransDA();
        private static readonly ILotAttributeDA lotAttributeDA = DataAccess.CreateLotAttributeDA();
        private static readonly ILpnDA lpn = DataAccess.CreateLpnDA();
        private PubParasInfo pubParasInfo;

        public AdjustmentBLL()
        {
            this.pubParasInfo = null;
        }

        public AdjustmentBLL(string currentWH)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(currentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(currentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001");
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002");
            }
        }

        public AdjustmentBLL(PubParasInfo tempPubParasInfo)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(tempPubParasInfo.CurrentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(tempPubParasInfo.CurrentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001", this.pubParasInfo.UserLanguage);
                }
                else
                {
                    this.pubParasInfo = new PubParasInfo();
                    this.pubParasInfo = tempPubParasInfo;
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002", this.pubParasInfo.UserLanguage);
            }
        }

        public void AdjustInventoryQty(DataBase dataBase, DbTransaction tran, string lot, string loc, string lpnid, string skuid, string ownerid, string updateby, decimal qty, string whLoginID)
        {
            InvLotInfo invLotinfo = new InvLotInfo();
            invLotinfo = invLot.GetInvLotByID(dataBase, tran, lot, whLoginID);
            invLotinfo.UpdatedBy = updateby;
            invLotinfo.Qty += qty;
            invLot.UpdateInvLot(dataBase, tran, invLotinfo, InvLotUpdateType.Qty, whLoginID);
            InvLotLocLpnInfo invLotLocLpnInfo = new InvLotLocLpnInfo();
            invLotLocLpnInfo = invLotLocLpn.GetInvLotLocLpnByID(dataBase, tran, lot, loc, lpnid, whLoginID);
            invLotLocLpnInfo.Qty += qty;
            invLotLocLpnInfo.UpdatedBy = updateby;
            invLotLocLpn.UpdateInvLotLocLpn(dataBase, tran, invLotLocLpnInfo, InvLotLocLpnUpdateType.Qty, whLoginID);
            InvSkuLocInfo invskulocInfo = new InvSkuLocInfo();
            invskulocInfo = invskuloc.GetInvSkuLocByID(dataBase, tran, ownerid, skuid, loc, whLoginID);
            invskulocInfo.UpdatedBy = updateby;
            invskulocInfo.Qty += qty;
            invskuloc.UpdateInvSkuLoc(dataBase, tran, invskulocInfo, InvSkuLocUpdateType.Qty, whLoginID);
            LpnInfo lpnInfo = new LpnInfo();
            if (!string.IsNullOrEmpty(lpnid))
            {
                lpnInfo = lpn.GetLpnByID(dataBase, tran, lpnid, whLoginID);
                if (lpnInfo != null)
                {
                    lpnInfo.Qty += qty;
                    lpnInfo.UpdatedBy = updateby;
                    lpn.UpdateLpn(dataBase, tran, lpnInfo, LpnUpdateType.Qty, whLoginID);
                }
            }
        }

        public string DeleteAdJustMent(List<string> IDS)
        {
            string temp = string.Empty;
            try
            {
                List<AdjustmentInfo> adjustmentInfos = new List<AdjustmentInfo>();
                AdjustmentInfo adjustmentInfo = null;
                foreach (string id in IDS)
                {
                    adjustmentInfo = adjustmentDA.GetAdjustmentByID(id, this.dataBaseID[0]);
                    adjustmentInfos.Add(adjustmentInfo);
                }
                AuditDataBLL auditDataBLL = new AuditDataBLL();
                if (adjustmentDA.DeleteAdjustment(IDS, this.dataBaseID[0]) > 0)
                {
                    for (int i = 0; i < IDS.Count; i++)
                    {
                        auditDataBLL.InsertAuditData<AdjustmentInfo>(adjustmentInfos[i], null, AuditAction.Delete, this.pubParasInfo.UserID, "ADJUSTMENT", this.dataBaseID[0]);
                        temp = temp + IDS[i] + ",";
                    }
                    return temp.Substring(0, temp.Length - 1);
                }
            }
            catch (Exception ex)
            {
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            return temp;
        }

        public string ExecuteInvAdjustment(AdjustmentDetailInfo AdjustmentDetail)
        {
            string whLoginID = this.dataBaseID[0];
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                InboundHelper inbound = new InboundHelper();
                AdjustmentInfo adjustmentInfo = adjustmentDA.GetAdjustmentByID(dataBase, tran, AdjustmentDetail.AdjustmentID, whLoginID);
                AdjustmentDetail.AdjustmentDate = adjustmentInfo.AdjustmentDate;
                string transID = this.InsertAdjustmentTrans(dataBase, tran, AdjustmentDetail, whLoginID);
                AdjustmentDetail.TransID = transID;
                adjustmentdetailDA.InsertAdjustmentDetail(dataBase, tran, AdjustmentDetail, whLoginID);
                this.AdjustInventoryQty(dataBase, tran, AdjustmentDetail.Lot, AdjustmentDetail.Loc, AdjustmentDetail.LpnID, AdjustmentDetail.SkuID, AdjustmentDetail.OwnerID, AdjustmentDetail.UpdatedBy, AdjustmentDetail.Qty, whLoginID);
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return AdjustmentDetail.AdjustmentID;
        }

        public AdjustmentInfo GetAdJustMentInfoByID(string id)
        {
            AdjustmentInfo adjustment = adjustmentDA.GetAdjustmentByID(id, this.dataBaseID[0]);
            if (adjustment != null)
            {
                adjustment.AdjustmentDetail = adjustmentdetailDA.GetAdjustmentDetailListByID(id, this.dataBaseID[0]);
            }
            return adjustment;
        }

        public DataSet GetAdJustMentInfoByQueryEntity(AdjustmentQueryEntity adjumentEntity)
        {
            List<string> sqlWhere = new List<string>();
            if (!string.IsNullOrEmpty(adjumentEntity.AdjustmentID))
            {
                sqlWhere.Add(" A.ADJUSTMENT_ID " + adjumentEntity.AdjustmentID);
            }
            if (!string.IsNullOrEmpty(adjumentEntity.AdjustmentDate))
            {
                sqlWhere.Add(adjumentEntity.AdjustmentDate.Replace("@AdJustMentDate@", " A.ADJUSTMENT_DATE "));
            }
            if (!string.IsNullOrEmpty(adjumentEntity.IsActive))
            {
                sqlWhere.Add(" A.IS_ACTIVE " + adjumentEntity.IsActive);
            }
            if (!string.IsNullOrEmpty(adjumentEntity.WhID))
            {
                sqlWhere.Add(" A.WH_ID " + adjumentEntity.WhID);
            }
            if (!string.IsNullOrEmpty(adjumentEntity.OwnerID))
            {
                sqlWhere.Add(" A.OWNER_ID " + adjumentEntity.OwnerID);
            }
            if (!string.IsNullOrEmpty(adjumentEntity.ReceiptID))
            {
                sqlWhere.Add(" B.RECEIPT_ID " + adjumentEntity.ReceiptID);
            }
            if (!string.IsNullOrEmpty(adjumentEntity.ReasonCode))
            {
                sqlWhere.Add(" B.REASON_CODE " + adjumentEntity.ReasonCode);
            }
            return adjustmentDA.GetAdjustmentByQueryList(sqlWhere, adjumentEntity, this.dataBaseID[0], this.pubParasInfo);
        }

        public DataSet GetAllAdJustMentInfo()
        {
            return adjustmentDA.GetAllAdjustment(this.dataBaseID[0]);
        }

        public string InsertAdJustMent(AdjustmentInfo obj)
        {
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            string AdJustMent = string.Empty;
            try
            {
                if (!DataAccess.CreateOwnerDA().CheckTradePartnerIDUnique(obj.OwnerID, this.dataBaseID[0]))
                {
                    PublicMethod.GetInstance().ShowAlertMessage("F5150_001", this.pubParasInfo.UserLanguage, new List<string> { obj.OwnerID });
                }
                else if (!commonMethod.CheckAuthorizationOwnerByUserID(this.pubParasInfo.UserID, obj.OwnerID))
                {
                    PublicMethod.GetInstance().ShowAlertMessage("F5150_002", this.pubParasInfo.UserLanguage, new List<string> { obj.OwnerID });
                }
                obj.AdjustmentID = commonMethod.GenNextNumStr(dataBase, tran, "ADJUSTMENT", this.dataBaseID[0]);
                obj.UpdatedBy = obj.CreatedBy;
                obj.CreatedDate = DateTime.Now;
                obj.UpdatedDate = DateTime.Now;
                if (adjustmentDA.InsertAdjustment(dataBase, tran, obj, this.dataBaseID[0]) > 0)
                {
                    AdJustMent = obj.AdjustmentID;
                    new AuditDataBLL().InsertAuditData<AdjustmentInfo>(dataBase, tran, null, obj, AuditAction.Insert, this.pubParasInfo.UserID, "ADJUSTMENT", this.dataBaseID[0]);
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            return AdJustMent;
        }

        private string InsertAdjustmentTrans(DataBase dataBase, DbTransaction tran, AdjustmentDetailInfo AdjustmentDetail, string whLoginID)
        {
            string transID = commonMethod.GenNextNumStr(dataBase, tran, "INV_TRANS", whLoginID);
            InvTransInfo invTransInfo = new InvTransInfo {
                TransID = transID,
                DocID = AdjustmentDetail.AdjustmentID,
                DocLineID = AdjustmentDetail.LineID,
                CaseCnt = AdjustmentDetail.CaseCnt,
                Cube = AdjustmentDetail.Cube,
                Descr = AdjustmentDetail.Descr,
                GrossWgt = AdjustmentDetail.GrossWgt,
                InnerPack = AdjustmentDetail.InnerPack,
                NetWgt = AdjustmentDetail.NetWgt,
                OtherUnit1 = AdjustmentDetail.OtherUnit1,
                OtherUnit2 = AdjustmentDetail.OtherUnit2,
                OwnerID = AdjustmentDetail.OwnerID,
                PackID = AdjustmentDetail.PackID,
                Pallet = AdjustmentDetail.Pallet,
                Qty = AdjustmentDetail.Qty,
                ReceiptID = AdjustmentDetail.ReceiptID,
                ReceiptLineID = AdjustmentDetail.ReceiptLineID,
                SkuID = AdjustmentDetail.SkuID,
                Status = TransStatus.OK,
                TransType = TransType.Adjustment,
                UomID = AdjustmentDetail.UomID,
                SourceTransType = TransSourceType.AdjustmentDetailAdd,
                ReceiptDate = DateTime.Now,
                FromLoc = AdjustmentDetail.Loc,
                FromLpnID = AdjustmentDetail.LpnID,
                ToLoc = AdjustmentDetail.Loc,
                ToLpnID = AdjustmentDetail.LpnID
            };
            LotAttributeInfo lotAttributeInfo = lotAttributeDA.GetLotAttributeByID(dataBase, tran, AdjustmentDetail.Lot, whLoginID);
            if (lotAttributeInfo != null)
            {
                invTransInfo.Lot = lotAttributeInfo.Lot;
                invTransInfo.LotAttr01 = lotAttributeInfo.LotAttr01;
                invTransInfo.LotAttr02 = lotAttributeInfo.LotAttr02;
                invTransInfo.LotAttr03 = lotAttributeInfo.LotAttr03;
                invTransInfo.LotAttr04 = lotAttributeInfo.LotAttr04;
                invTransInfo.LotAttr05 = lotAttributeInfo.LotAttr05;
                invTransInfo.LotAttr06 = lotAttributeInfo.LotAttr06;
                invTransInfo.LotAttr07 = lotAttributeInfo.LotAttr07;
                invTransInfo.LotAttr08 = lotAttributeInfo.LotAttr08;
                invTransInfo.LotAttr09 = lotAttributeInfo.LotAttr09;
                invTransInfo.LotAttr10 = lotAttributeInfo.LotAttr10;
                invTransInfo.ExpiryDate = lotAttributeInfo.ExpiryDate;
                invTransInfo.ReceiptDate = lotAttributeInfo.ReceiptDate;
                invTransInfo.ProduceDate = lotAttributeInfo.ProduceDate;
                invTransInfo.ExternalLot = lotAttributeInfo.ExternalLot;
                invTransInfo.VendorID = lotAttributeInfo.VendorID;
            }
            invTransInfo.TransDate = (AdjustmentDetail.AdjustmentDate != new DateTime()) ? AdjustmentDetail.AdjustmentDate : DateTime.Now;
            invTransInfo.CreatedBy = AdjustmentDetail.CreatedBy;
            invTransInfo.UpdatedBy = invTransInfo.CreatedBy;
            InvLotInfo invLotInfo = invLot.GetInvLotByID(dataBase, tran, AdjustmentDetail.Lot, whLoginID);
            if (invLotInfo != null)
            {
                invTransInfo.UnitPrice = invLotInfo.UnitPrice;
            }
            invTranDA.InsertInvTrans(dataBase, tran, invTransInfo, whLoginID);
            return transID;
        }

        public string UpdateAdJustMent(AdjustmentInfo obj)
        {
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            string AdJustMentID = string.Empty;
            try
            {
                AdjustmentInfo oldadjustmentInfo = adjustmentDA.GetAdjustmentByID(dataBase, tran, obj.AdjustmentID, this.dataBaseID[0]);
                if (adjustmentDA.UpdateAdjustment(dataBase, tran, obj, this.dataBaseID[0]) > 0)
                {
                    AdJustMentID = obj.AdjustmentID;
                    new AuditDataBLL().InsertAuditData<AdjustmentInfo>(dataBase, tran, oldadjustmentInfo, obj, AuditAction.Update, this.pubParasInfo.UserID, "ADJUSTMENT", this.dataBaseID[0]);
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return AdJustMentID;
        }
    }
}

